package cn.ly817.jay.controller;

import cn.ly817.jay.DTO.DailyNote;
import cn.ly817.jay.DTO.JSONResult;
import cn.ly817.jay.entity.Mission;
import cn.ly817.jay.entity.Note;
import cn.ly817.jay.entity.User;
import cn.ly817.jay.enums.MissionGrade;
import cn.ly817.jay.enums.MissionState;
import cn.ly817.jay.exceptions.NoteMultiMissionException;
import cn.ly817.jay.service.MissionService;
import cn.ly817.jay.service.NoteService;
import cn.ly817.jay.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by LuoYu on 2016/12/8.
 */
@Controller
@RequestMapping("/t")
public class TaskController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MissionService missionService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private UserService userService;
    //==================================content=====================================
    /**
     * 当前用户任务列表
     */
    @RequestMapping(value = "/m/list",method = RequestMethod.GET)
    public String list(HttpSession session,Model model){
        User loginUser = (User)session.getAttribute("loginUser");
        //查询用户本月已完成、未完成任务:需不需要本月
        List unhandledMissions = missionService.getUnhandledMissionListBypProcessorId(loginUser.getId());
        List finishedMissions = missionService.getFinishedMissionListBypProcessorId(loginUser.getId());
        model.addAttribute("unhandledMissions",unhandledMissions);
        model.addAttribute("finishedMissions",finishedMissions);
        return "/content/home_b_mission_list";
    }

    /**
     * 指定任务详情
     */
    @RequestMapping(value = "/m/{missionId}/detail")
    public String missionDetail(@PathVariable("missionId") Long missionId,Model model){
        Mission mission = missionService.getMissionDetailById(missionId);
        model.addAttribute("mission",mission);
        return "content/home_c_mission_detail";
    }

    /**
     * 生成本周日志列表
     */
    @RequestMapping(value = "/n/recordList",method = RequestMethod.GET)
    public String recordList(HttpSession session,Model model){
        User loginUser = (User)session.getAttribute("loginUser");
        List thisWeek = noteService.getThisWeekDaily(loginUser.getId());
        model.addAttribute("thisWeek",thisWeek);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        model.addAttribute("todayIndex", c.get(Calendar.DAY_OF_WEEK));
        return "/content/home_b_daily_list";
    }

    /**
     * 跳转到写日志页
     */
    @RequestMapping(value = "/n/{weekIndex}/writeDaily",method = RequestMethod.GET)
    public String writeDaily(@PathVariable("weekIndex") int weekIndex,Model model){
        model.addAttribute("weekIndex",weekIndex);
        return "/content/home_c_write_daily";
    }

    /**
     * 根据daily noteId获取详情
     */
    @RequestMapping(value = "/n/{dailyId}/dailyDetail",method = RequestMethod.GET)
    public String dailyDetail(@PathVariable("dailyId")Long dailyId,Model model){
        Note daily = noteService.getDailyById(dailyId);
        model.addAttribute("daily",daily);
        return "/content/home_c_daily_detail";
    }

    /**
     * b栏 组长待审查任务单列表
     * "/t/n/checkList"
     */
    @RequestMapping(value = "/n/checkList",method = RequestMethod.GET)
    public String checkList(HttpSession session,Model model){
        User loginUser = (User)session.getAttribute("loginUser");
        List unhandledNotes =  noteService.getUnhandledNotesByLeaderId(loginUser.getId());
        List handledNotes = noteService.getHandledNotesByLeaderId(loginUser.getId());
        model.addAttribute("unhandledNotes",unhandledNotes);
        model.addAttribute("handledNotes",handledNotes);
        return "/content/home_b_check_list";
    }
    @RequestMapping(value = "/n/{noteId}/noteDetail")
    public String noteDetail(@PathVariable("noteId")long noteId,Model model){
        Note note = noteService.getNoteDetail(noteId);
        //TODO 写在构造方法中
//        note.getMission().setScore(MissionGrade.scoreOf(note.getMission().getMissionGrade()));
//        note.getMission().setGRADE(MissionGrade.stateOf(note.getMission().getMissionGrade()).toString());
        model.addAttribute("noteDetail", note);
        model.addAttribute("sliderInit", note.getCompleteness()*100);
        return "/content/home_c_note_detail";
    }
    //================================JSON==================================
    /**
     * 任务条提交
     */
    @RequestMapping(value = "/n/noteSubmit",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONResult<Map> noteSubmit(HttpSession session,
                                         int complete,
                                         int svnRev,
                                         String detail,
                                         long missionId){
        User loginUser = (User)session.getAttribute("loginUser");
        JSONResult<Map> result;
        //生成任务对应的任务条{type=1,state=false}
        Note missionNote = new Note(1,missionId,detail,complete/(float)100,false,svnRev,new Date(),
                loginUser.getId(),missionService.getMissionOriginatorById(missionId));
        try {
            noteService.saveNewMissionNote(missionNote);
            Map data = new HashMap();
            data.put("missionId",missionId);
            data.put("unhandledNum",missionService.getUnhandledMissionNumByUserId(loginUser.getId()));
            result = new JSONResult<Map>(true,data);
        } catch (NoteMultiMissionException e) {
            logger.error("数据插入逻辑错误》》》"+e.getMessage());
            result = new JSONResult<Map>(false,e.getMessage());
        }
        return result;
    }
    /**
     * 日志提交
     * data中返回dailyId
     */
    @RequestMapping(value = "/n/dailySubmit",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONResult<Map> dailySubmit(HttpSession session,
                                       String dailyTitle,
                                       String dailyDetail,
                                       int weekIndex
                                       ){
        User loginUser = (User)session.getAttribute("loginUser");
        JSONResult<Map> result;
        boolean state = false;//true-当天日志  false-补写日志
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        int todayIndex = c.get(Calendar.DAY_OF_WEEK);
        if(todayIndex == weekIndex){
            state = true;
        }
        //calender实例中指向的是今天
        c.set(Calendar.DAY_OF_WEEK,weekIndex);
        Date dateMark = c.getTime();
        Note dailyNote = new Note(2,dailyDetail,dailyTitle,dateMark,state,
                loginUser.getId(),userService.getUsersLeaderId(loginUser.getId()));
        noteService.saveNewDailyNote(dailyNote);
        Map data = new HashMap();
        data.put("dailyId",dailyNote.getId());
        result = new JSONResult<Map>(true,data);
        return result;
    }

    /**
     * 组员接收任务
     */
    @RequestMapping(value = "/m/{missionId}/acceptMission",
            method = RequestMethod.GET,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONResult<Map> acceptMission(@PathVariable("missionId") Long missionId){
        JSONResult<Map> result = null;
        //TODO enums
        missionService.updateStateById(missionId,MissionState.HANDLING.getDbState());
        Map data = new HashMap();
        data.put("missionId",missionId);
        result = new JSONResult<Map>(true,data);
        return result;
    }
    /**
     * 组长审批提交
     * 修改note状态&修改mission状态
     */
    @RequestMapping(value = "/n/noteCheckSubmit",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONResult<Map> noteCheckSubmit(HttpSession session,
                                           int complete,
                                           String comment,
                                           long noteId){
        User loginUser = (User)session.getAttribute("loginUser");
        JSONResult<Map> result;
        //完成度和missionId
        Note note = noteService.getCheckNoteById(noteId);
        note.setComment(comment);
        if(complete > -1){//修改了完成度,note状态true，更新分数，mission状态 改为2
            float completeness = complete/100.0f;
            note.setCompleteness(completeness);
            note.setState(true);
            note.setScore(MissionGrade.scoreOf(note.getMission().getMissionGrade())*completeness);
            missionService.updateStateById(note.getMission().getId(), MissionState.PASSED.getDbState());
        }else {//不修改完成度和note状态，mission状态改为 -2
            missionService.updateStateById(note.getMission().getId(), MissionState.FAILED.getDbState());
        }
        noteService.checkSubmit(note);
        Map data = new HashMap();
        data.put("noteId",note.getId());
        data.put("unhandledNum",noteService.getHandledNotesByLeaderId(loginUser.getId()));
        result = new JSONResult<Map>(true,data);
        return result;
    }
}
